// 收到4开头的消息
import { resArr } from '../socketOnMessageTools'
import { ifContactInList, decryptMessage } from '../socketTools'
import { Message } from 'element-ui'
import store from '@/store'
import tools from '@/utils/tools'
import router from '@/router'

// 解析消息
const decryptMsg = decryptMessage
// 判断缓存的用户列表中是否有该用户
const ifContactInContactlist = ifContactInList

export default async (type, result) => {
  switch (type) {
    // 会议-某人加入会议（发给其他人）
    case '4.1.3': {
      decryptMsg(result.body, ['cf_id', 'id', 'voiced', 'camera'], 0)
      const realData = resArr[0]
      await ifContactInContactlist(realData.id, 1)
      store.commit('conferenceRoom/add_cf_member', {
        id: realData.id,
        voiced: realData.voiced,
        camera: realData.camera,
        stream: new MediaStream(),
        peer: null
      })
      tools.webRTC.getPeerConnection(realData.id).then(peer => {
        // 获取自身媒体流
        const localStream = tools.webRTC.getLocalStream()
        if (localStream && localStream.active) {
          tools.webRTC.addTracks(peer, localStream)
          tools.webRTC.createOffer(peer, realData.cf_id, realData.id)
        } else {
          let temp = 0
          const timer = setInterval(() => {
            const stream = tools.webRTC.getLocalStream()
            if (stream && stream.active) {
              tools.webRTC.addTracks(peer, stream)
              tools.webRTC.createOffer(peer, realData.cf_id, realData.id)
              clearInterval(timer)
            } else {
              temp++
              if (temp > 20) {
                clearInterval(timer)
              }
            }
          }, 100)
        }
      })
      break
    }
    // 会议-某人离开会议（发给其他人）
    case '4.1.5': {
      decryptMsg(result.body, ['cf_id', 'id'], 0)
      const realData = resArr[0]
      if (realData.cf_id === store.state.conferenceRoom.cf_id) {
        // 关闭与当前成员的peer
        store.commit('conferenceRoom/close_peer', realData.id)
        // 会议成员中剔除该成员
        store.commit('conferenceRoom/remove_member', realData.id)
      }
      break
    }
    // 会议-被邀请加入会议
    case '4.1.7': {
      decryptMsg(result.body, ['id', 'cf_id', 'cf_name'], 0)
      const realData = resArr[0]
      store.dispatch('conference/getCfDetail', realData.cf_id).then(detail => {
        if (detail.data && detail.data.code === 200) {
          store.commit('chatInformation/set_topContact', {
            id: 'notification',
            id_type: 0
          })
          // 判断当前联系人是否为消息通知
          if (store.state.chatInformation.current_contact && store.state.chatInformation.current_contact.id === 'notification' && store.state.chatInformation.current_contact.id_type === 0) {
            store.dispatch('chatInformation/setAddMessage', {
              message: {
                id: 'notification',
                isSelf: false,
                msg_id: realData.cf_id,
                type: 'notice',
                timestamp: +new Date(),
                noticeType: detail.data.data.cf_state,
                cf_name: detail.data.data.cf_name,
                cf_sponsor_name: detail.data.data.cf_sponsor_name,
                cf_plan_participant_count: detail.data.data.cf_plan_participant_count,
                unread: false
              },
              id: 'notification',
              idType: 0
            })
          } else {
            store.dispatch('chatInformation/setAddMessage', {
              message: {
                id: 'notification',
                isSelf: false,
                msg_id: realData.cf_id,
                type: 'notice',
                timestamp: +new Date(),
                noticeType: detail.data.data.cf_state,
                cf_name: detail.data.data.cf_name,
                cf_sponsor_name: detail.data.data.cf_sponsor_name,
                cf_plan_participant_count: detail.data.data.cf_plan_participant_count,
                unread: true
              },
              id: 'notification',
              idType: 0
            })
          }
        }
      })
      break
    }
    // 会议-某人被邀请加入会议
    case '4.1.8': {
      decryptMsg(result.body, ['id', 'cf_id', 'cf_invited'], 0)
      const realData = resArr[0]
      if (store.state.conferenceRoom.cf_id === realData.cf_id) {
        realData.cf_invited.forEach(item => {
          item = {
            id: item
          }
          ifContactInList(item, 1)
          store.commit('conferenceRoom/add_cf_invited', item)
        })
      }
      break
    }
    // 会议-被踢出会议
    case '4.1.10': {
      decryptMsg(result.body, ['cf_id'], 0)
      const realData = resArr[0]
      if (realData.cf_id === store.state.conferenceRoom.cf_id) {
        store.commit('conferenceRoom/close_allPeer')
        store.commit('conferenceRoom/set_cf_notification', 3)
      }
      break
    }
    // 会议-某人被踢出会议
    case '4.1.11': {
      decryptMsg(result.body, ['cf_id', 'id'], 0)
      const realData = resArr[0]
      if (realData.cf_id === store.state.conferenceRoom.cf_id) {
        store.commit('conferenceRoom/close_peer', realData.id)
        store.commit('conferenceRoom/remove_member', realData.id)
      }
      break
    }
    // 会议-静音所有人
    case '4.1.12': {
      decryptMsg(result.body, ['cf_id'], 0)
      const realData = resArr[0]
      if (realData.cf_id === store.state.conferenceRoom.cf_id) {
        if (!tools.isSelf(store.state.conferenceRoom.cf_host)) {
          Message({
            type: 'info',
            message: '主持人已将全体成员静音'
          })
          tools.webRTC.muteMicPhone()
          store.commit('conferenceRoom/set_conferenceSettings_voiced', false)
        }
        // 遍历关闭所有人麦克风
        store.state.conferenceRoom.cf_members.forEach(item => {
          if (!tools.conference.isHost(item.id)) {
            store.commit('conferenceRoom/set_cf_member_device', {
              id: item.id,
              type: 'voiced',
              status: false
            })
          }
        })
        // 设置会议状态属性-是否静音所有人
        store.commit('conferenceRoom/set_cf_mute_all', true)
      }
      break
    }
    // 会议-主持人取消全体静音
    case '4.1.14': {
      decryptMsg(result.body, ['cf_id'], 0)
      const realData = resArr[0]
      if (realData.cf_id === store.state.conferenceRoom.cf_id) {
        // 设置会议状态属性-是否静音所有人
        store.commit('conferenceRoom/set_cf_mute_all', false)
        if (!tools.conference.isHost(tools.getUserId())) {
          store.commit('conferenceRoom/set_cf_relieve', true)
        }
      }
      break
    }
    // 会议-被主持人静音（发给被静音成员）
    case '4.1.16': {
      decryptMsg(result.body, ['cf_id'], 0)
      const realData = resArr[0]
      if (realData.cf_id === store.state.conferenceRoom.cf_id) {
        Message({
          type: 'info',
          message: '主持人已将您静音'
        })
        tools.webRTC.muteMicPhone()
        store.commit('conferenceRoom/set_conferenceSettings_voiced', false)
        store.commit('conferenceRoom/set_cf_member_device', {
          id: store.state.user.userInfo.user_id,
          type: 'voiced',
          status: false
        })
      }
      break
    }
    // 会议-某人被主持人静音
    case '4.1.17': {
      decryptMsg(result.body, ['cf_id', 'id'], 0)
      const realData = resArr[0]
      if (realData.cf_id === store.state.conferenceRoom.cf_id) {
        store.commit('conferenceRoom/set_cf_member_device', {
          id: realData.id,
          type: 'voiced',
          status: false
        })
      }
      break
    }
    // 会议-请求取消静音（发给被操作者）
    case '4.1.19': {
      decryptMsg(result.body, ['cf_id'], 0)
      const realData = resArr[0]
      if (realData.cf_id === store.state.conferenceRoom.cf_id && !tools.conference.isHost(store.state.user.userInfo.user_id)) {
        store.commit('conferenceRoom/set_cf_relieve', true)
      }
      break
    }
    // 会议-某人打开或关闭麦克风
    case '4.1.21': {
      decryptMsg(result.body, ['cf_id', 'id', 'cf_operation'], 0)
      const realData = resArr[0]
      if (realData.cf_id === store.state.conferenceRoom.cf_id) {
        if (tools.isSelf(realData.id)) {
          if (realData.cf_operation) {
            tools.webRTC.cancelMuteMicPhone()
          } else {
            tools.webRTC.muteMicPhone()
          }
          store.commit('conferenceRoom/set_conferenceSettings_voiced', realData.cf_operation)
        }
        store.commit('conferenceRoom/set_cf_member_device', {
          id: realData.id,
          type: 'voiced',
          status: realData.cf_operation
        })
      }
      break
    }
    // 会议-某人打开或关闭摄像头
    case '4.1.23': {
      decryptMsg(result.body, ['cf_id', 'id', 'cf_operation'], 0)
      const realData = resArr[0]
      if (realData.cf_id === store.state.conferenceRoom.cf_id) {
        if (tools.isSelf(realData.id)) {
          if (realData.cf_operation) {
            tools.webRTC.openCamera()
          } else {
            tools.webRTC.closeCamera()
          }
          store.commit('conferenceRoom/set_conferenceSettings_camera', realData.cf_operation)
        }
        store.commit('conferenceRoom/set_cf_member_device', {
          id: realData.id,
          type: 'camera',
          status: realData.cf_operation
        })
      }
      break
    }
    // 会议-是否锁定会议(群成员）
    case '4.1.24': {
      decryptMsg(result.body, ['cf_id', 'cf_operation'], 0)
      const realData = resArr[0]
      if (store.state.conferenceRoom.cf_id === realData.cf_id) {
        store.commit('conferenceRoom/set_cf_isLocked', realData.cf_operation)
      }
      break
    }
    // 会议-被设为主持人
    case '4.1.26': {
      decryptMsg(result.body, ['cf_id'], 0)
      const realData = resArr[0]
      if (store.state.conferenceRoom.cf_id === realData.cf_id) {
        store.commit('conferenceRoom/set_cf_host', store.state.user.userInfo.user_id)
        store.commit('conferenceRoom/set_cf_notification', 1)
      }
      break
    }
    // 会议-某人被设置为主持人
    case '4.1.27': {
      decryptMsg(result.body, ['cf_id', 'id'], 0)
      const realData = resArr[0]
      if (store.state.conferenceRoom.cf_id === realData.cf_id) {
        store.commit('conferenceRoom/set_cf_host', realData.id)
        Message({
          type: 'info',
          message: tools.getContactInfo(realData.id, 1).user_name + '已被设为主持人'
        })
      }
      break
    }
    // 会议-主持人被收回
    case '4.1.29': {
      decryptMsg(result.body, ['cf_id', 'id'], 0)
      const realData = resArr[0]
      if (store.state.conferenceRoom.cf_id === realData.cf_id) {
        store.commit('conferenceRoom/set_cf_host', store.state.conferenceRoom.cf_sponsor)
        if (tools.isSelf(store.state.conferenceRoom.cf_sponsor)) {
          store.commit('conferenceRoom/set_cf_notification', 1)
        } else {
          Message({
            type: 'info',
            message: tools.getContactInfo(store.state.conferenceRoom.cf_sponsor, 1).user_name + '已被设为主持人'
          })
        }
      }
      break
    }
    // 会议-会议结束
    case '4.1.30': {
      decryptMsg(result.body, ['cf_id'], 0)
      const realData = resArr[0]
      if (store.state.conferenceRoom.cf_id === realData.cf_id) {
        store.commit('conferenceRoom/close_allPeer')
        // 判断是否是主持人
        if (tools.conference.isHost(store.state.user.userInfo.user_id)) {
          Message({
            type: 'info',
            message: '会议已结束'
          })
          store.commit('conferenceRoom/reset_state')
          router.push('/conference/agendaCf/main')
        } else {
          store.commit('conferenceRoom/set_cf_notification', 2)
        }
      }
      break
    }
    // 会议-收到文本消息
    case '4.2.2': {
      decryptMsg(result.body, ['cf_id', 'id', 'cf_msg'], 0)
      const realData = resArr[0]
      if (store.state.conferenceRoom.cf_id === realData.cf_id) {
        store.commit('conferenceRoom/set_cf_chatContent', {
          list: [
            {
              msg: realData.cf_msg,
              msgID: +new Date(),
              from: realData.id
            }
          ]
        })
      }
      break
    }
    // 会议-收到p2p消息
    case '4.2.4': {
      decryptMsg(result.body, ['p2p_type', 'cf_id', 'id', 'p2p_msg'], 0)
      const realData = resArr[0]
      switch (realData.p2p_type) {
        // 接收到offer
        case 1: {
          tools.webRTC.getPeerConnection(realData.id).then(peer => {
            const localStream = tools.webRTC.getLocalStream()
            if (localStream && localStream.active) {
              tools.webRTC.addTracks(peer, localStream)
              const sdp = realData.p2p_msg
              tools.webRTC.createAnswer(peer, sdp, realData.cf_id, realData.id)
            } else {
              const timer = setInterval(() => {
                const stream = tools.webRTC.getLocalStream()
                if (stream && stream.active) {
                  tools.webRTC.addTracks(peer, stream)
                  const sdp = realData.p2p_msg
                  tools.webRTC.createAnswer(peer, sdp, realData.cf_id, realData.id)
                  clearInterval(timer)
                }
              }, 100)
            }
          })
          break
        }
        // 接收到answer
        case 2: {
          const peer = store.state.conferenceRoom.cf_members.filter(item => item.id === realData.id)[0].peer
          const sdp = realData.p2p_msg
          tools.webRTC.createRemoteSDP(peer, sdp)
          break
        }
        case 3: {
          // 接收到candidate
          const sdpMid = realData.p2p_msg.candidate_type === 1 ? '0' : '1'
          const sdpMLineIndex = realData.p2p_msg.candidate_type === 1 ? 0 : 1
          const candidate = realData.p2p_msg.candidate_content
          store.commit('conferenceRoom/add_iceCandidate', {
            id: realData.id,
            sdpMid,
            sdpMLineIndex,
            candidate
          })
          break
        }
        case 4: {
          // 接收到重连
          store.commit('conferenceRoom/close_peer', realData.id)
          store.commit('conferenceRoom/reset_mediaStream', realData.id)
          tools.webRTC.getPeerConnection(realData.id).then(peer => {
            if (tools.webRTC.getLocalStream().active) {
              tools.webRTC.addTracks(peer, tools.webRTC.getLocalStream())
              // 发送offer
              tools.webRTC.createOffer(peer, realData.cf_id, realData.id)
            } else {
              tools.webRTC.openMedia({}).then(stream => {
                tools.webRTC.addTracks(peer, stream)
                // 发送offer
                tools.webRTC.createOffer(peer, realData.cf_id, realData.id)
              })
            }
          })
          break
        }
      }
      break
    }
  }
}
